package org.web.datajpa.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.web.datajpa.constant.ResultEnum;
import org.web.datajpa.domain.Student;
import org.web.datajpa.exception.ResultException;
import org.web.datajpa.repository.StudentRepository;

import java.util.List;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;
    // 获取所有学生信息
    public List<Student> findAll() {
        return studentRepository.findAll();
    }
    // 添加学生信息
    public Student add(Student student) { return studentRepository.save(student);}
    // 更新学生信息
    public Student update(Student student) {
        return studentRepository.save(student);
    }
    // 删除学生信息
    public void deleteById(Long id) {
        studentRepository.deleteById(id);
    }
    // 根据id查找学生信息
    public Student findById(Long id) {
        return studentRepository.findById(id).orElse(null);
    }
    // 根据姓名查找学生信息
    public List<Student> searchByName(String name) {
        return studentRepository.findByNameContaining(name);
    }

    // 登录验证-验证学号和密码是否匹配
    public Student validateIdAndPwd(Long id, String password) throws Exception{
        Student student = studentRepository.findById(id).orElse(null);
        if (student != null && student.getPassword().equals(password)) {
            //匹配
            return student;
        }else{
            throw new ResultException(ResultEnum.LOGIN_ERROR);
        }
    }

    // 分页查询
    public Page<Student> getAll(Pageable pageable){
        return studentRepository.findAll(pageable);
    }
    // 分页查询
    public Page<Student> getAll(Example<Student> example, Pageable pageable){
        return studentRepository.findAll(example,pageable);
    }


    // 根据id批量删除学生
    @Transactional
    public void deleteStudentsByIds(List<Integer> ids) {
        if (ids != null && !ids.isEmpty()) {
            studentRepository.deleteByIds(ids);
        } else {
            throw new ResultException("学号ID列表不能为空");
        }
    }



}
